from django.contrib.auth.models import AbstractUser
from django.db import models

from drf_admin_base.utils.models import BaseModel
from system.models import UsersRoles, RolesPermissions


class Users(AbstractUser, BaseModel):
    """
    用户
    """
    full_name = models.CharField(max_length=20, verbose_name='姓名')
    phone = models.CharField(max_length=11, verbose_name='手机号')
    login_fail_num = models.IntegerField(default=0, verbose_name='登录尝试次数')
    is_lock = models.BooleanField(default=False, verbose_name='是否被锁定')
    icon = models.URLField(max_length=255, null=True, blank=True, verbose_name='图标')
    is_superuser = models.BooleanField(default=False, verbose_name='是否是超级用户')

    department = models.ForeignKey('system.Departments', models.DO_NOTHING, db_column='department_id')

    class Meta:
        managed = False  # Django不管理这个表的创建/删除
        db_table = 'oauth_users'
        verbose_name = '用户'
        verbose_name_plural = verbose_name
        ordering = ['update_datetime']

    def __str__(self):
        return self.full_name

    def _get_user_permissions(self):
        """获取用户权限"""
        users_roles = UsersRoles.objects.filter(user=self)
        permission_list = []
        for user_role in users_roles:
            if user_role.role.name == 'admin':
                permission_list.append('admin')
                continue
            role_permissions = RolesPermissions.objects.filter(role=user_role.role)
            if role_permissions:
                for role_permission in role_permissions:
                    permission_list.append(role_permission.permission.sign)

        permission_list = list(filter(None, set(permission_list)))
        return permission_list

    def get_user_info(self):
        # 获取用户信息
        user_info = {
            'id': self.pk,
            'username': self.username,
            'name': self.full_name,
            'avatar': '/media/' + str(self.icon),
            'email': self.email,
            'permissions': self._get_user_permissions(),
            'department': self.department.name if self.department else '',
            'mobile': '' if self.phone is None else self.phone
        }
        return user_info
